//
//  RACAndMVVMViewController01.m
//  RACExample
//
//  Created by 山刘 on 2020/5/29.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "RACAndMVVMViewController01.h"
#pragma mark - ====================M层====================
#pragma mark - ====================VM层====================
@interface RACAndMVVMViewModel01 : NSObject
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSString *searchText;

//创建一个绑定View的指令.RACCommand是ReactiveCocoa中呈现UI动作的组件.它包含一个来表示UI动作结果、当前状态、标明动作是否被执行的信号量.
@property (strong, nonatomic) RACCommand *executeSearch;
@end
@implementation RACAndMVVMViewModel01
- (instancetype)init {
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}
- (void)initialize {
    self.title = @"Flickr Search";
    [self checkSearchText];
}

// 这个方法中将执行一些业务逻辑作为执行命令的结果,并会通过信号异步地返回结果.
// 目前只完成了一个虚拟的执行情况;空信号立即完成.延迟操作增加了完成事件返回后的两秒延迟.用来使代码看起来更加真实.
- (RACSignal *)executeSearchSignal {
    return [[[[RACSignal empty]
              logAll]
             delay:2.0]
            logAll];
}
// 检查 searchText 输入的合法性
-(void)checkSearchText{
    
    /*[[RACObserve(self, searchText) map:^id _Nullable(NSString*  _Nullable value) {
     return @(value.length > 3);
     }] subscribeNext:^(id  _Nullable x) {
     NSLog(@"search text is valid %@", x);
     }];*/
    
    // distinctUntilChanged 只有输入合法才能进行打印
    RACSignal *validSearchSignal = [[RACObserve(self, searchText) map:^id _Nullable(NSString*  _Nullable value) {
        return @(value.length > 3);
    }]distinctUntilChanged];
    [validSearchSignal subscribeNext:^(id  _Nullable x) {
        NSLog(@"search text is valid %@", x);
    }];
    
    self.executeSearch = [[RACCommand alloc] initWithEnabled:validSearchSignal signalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [self executeSearchSignal];
    }];
}
@end

#pragma mark - ====================V层====================

@interface RACAndMVVMViewController01 ()
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (strong, nonatomic) RACAndMVVMViewModel01 *viewModel;
@end

@implementation RACAndMVVMViewController01

- (void)viewDidLoad {
    [super viewDidLoad];
    [self bindViewModel];
}
- (void)bindViewModel {
    self.title = self.viewModel.title;
    RAC(self.viewModel,searchText) = self.searchTextField.rac_textSignal;
    self.loginButton.rac_command = self.viewModel.executeSearch;
    
    [self.viewModel.executeSearch.executionSignals subscribeNext:^(id x) {
        [self.searchTextField resignFirstResponder];
    }];
}

-(RACAndMVVMViewModel01 *)viewModel{
    if (!_viewModel) {
        _viewModel = [[RACAndMVVMViewModel01 alloc] init];
    }
    return _viewModel;
}
@end
